<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/22
 * Time: 15:07
 */

namespace app\api\model;
use app\admin\model\LessonComment as LessonCommentModel;
use app\common\lib\exception\ApiException;
use think\Model;
use think\Log;
use think\Db;
use app\common\Str;


class LessonComment extends Model
{

    /**
     * @ 错过评论时间 默认为好评
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function editCommentStatus()
    {
        if (empty($_GET)) {
            throw new ApiException('数据不合法',404);
        }
        if (empty($_GET['id'])) {
            throw new ApiException('id is not found',404);
        }
        try {
            $id = $_GET['id'];
            $comment = Db::name('lesson_comment')
                ->alias("comment")
                ->where(array('comment_id' => $id, 'comment_status' => 0))
                ->join("lesson le",'comment.lesson_id = le.id','LEFT')
                ->field("comment.*,le.lesson_name")
                ->select();

            foreach ($comment as $k => $v) {

                if ($comment[$k]['comment_start_time'] != 0) {

                    if (date('Ymd', $comment[$k]['comment_start_time']) != date('Ymd', time())) {
                        $data['comment_status'] = 1;
                        $rec = $this->allowField(true)->where('id',$comment[$k]['id'])->update($data);
                        if (!$rec) {
                            return show(config('code.error'), '操作失败');
                        }
                        SendMessage($id,'课程评价','用户您好，您在上的课程：'.$comment[$k]['lesson_name'].',已过评论时间，系统已默认为好评。');
                    }
                } else {

                }
            }

            return show(config('code.success'), '操作成功');
        } catch (\Exception $e) {
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 获取尚未评论的课程数
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function index(){
        if (empty($_GET)) {
            throw new ApiException('数据不合法',404);
        }
        //id int 评论用户id 必传
        if (empty($_GET['id'])) {
            throw new ApiException('id is not found',404);
        }
        try {
            $id = $_GET['id'];
            $comments = Db::name('lesson_comment');
            $comment = $comments
                ->where(array('comment_id' => $id, 'comment_status' => 0))
                ->field('id')
                ->count();

            return show(config('code.success'), '当前待评论条数:',$comment);

        } catch (\Exception $e) {
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * @添加评论信息
     * @author 巫玉梅 <1120504614@qq.com>
     * @param comment_content string 评论内容 选传
     * @return array|false|\PDOStatement|string|Model
     */
    public function editComment(){

        if(empty($_POST)){
            throw new ApiException('数据不合法',404);
        }
        // id int 用户id 必传
        if(empty($_POST['comment_id'])){
            throw new ApiException('comment_id is not found',404);
        }
        // lid 评论的课程id int 必传
        if(empty($_POST['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }
        //comment_rank int 评论等级 必传 非常满意（1）、满意（2）、基本满意（3）不太满意（4）或很不满意（5）
        if(empty($_POST['comment_rank'])){
            throw new ApiException('comment_rank is not found',404);
        }

        // 修改评论状态
        if(empty($_POST['comment_status'])){
            $_POST['comment_status'] = 1;
        }

        try{
            $data = special_str($_POST);
            $comment=$this
                ->allowField(true)
                ->where('lesson_id',$data['lesson_id'])
                ->where('comment_id',$data['comment_id'])
                ->update($data);
            if($comment){
                return show(config('code.success'),'评论成功');
            }else{
                return show(config('code.error'),'评论提交失败');
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }


    /**
     * @ 教师点名 获取上课名单
     * @param lesson_id int 课程详情id 必传
     * @author 巫玉梅 <1120504614@qq.com>
     */
    public function classNameList()
    {

        $data = $_POST;

        if (empty($data)) {
            throw new ApiException('数据不合法',404);
        }
        //lesson_id 课程详情id 必传
        if(empty($data['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }
        try{
            $info = Db::name('lesson')->where(array('id' => $data['lesson_id']))->find();
            if ($info['cost_type'] == 1){ //学费课从评论表拿取名单
                $where['lesson_id'] = $data['lesson_id'];
                $where['comment_rank'] = array('elt', 3);
                $name = Db::name('lesson_comment')
                    ->join('user us', 'comment_id=us.id', 'LEFT')
                    ->field('comment_id as user_id,
                            us.full_name,us.sex,us.tel')
                    ->where($where)
                    ->select();

                return show(config('code.success'), '获取数据成功', $name, 200);


            }elseif ($info['cost_type'] == 2){  // 学币课从订单表拿取名单
                $name = Db::name('order')->where(array('lesson_id' => $data['lesson_id']))
                    ->join('user us', 'user_id=us.id', 'LEFT')
                    ->field('user_id,us.full_name,us.sex,us.tel')
                    ->select();

                return show(config('code.success'), '获取数据成功', $name, 200);
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * @到课(学生出勤)情况处理
     * @param lesson_id int 课程id
     * @param user_id int array 到课人员
     * @author 巫玉梅 <1120504614@qq.com>
     * @return
     */
    public function attendLesson()
    {
        $data = $_POST;

        if (empty($data)) {
            throw new ApiException('数据不合法',404);
        }
        //lesson_id 课程详情id 必传
        if(empty($data['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }
        //user_id 用户id 必传
        if(empty($data['user_id'])){

            throw new ApiException('user_id is not found',404);

        }elseif(!empty($data['user_id'])){

            if(is_array(json_decode($data['user_id']))){
                $data['user_id'] = json_decode($data['user_id']);
            }

        }
        Db::startTrans();//开启事务
        try {
            $info = Db::name('lesson')->where(array('id' => $data['lesson_id']))->find();
            $info_res = Db::name('lesson')
                ->where('id', $data['lesson_id'])
                ->setField('com_lesson_num', $info['com_lesson_num'] + 1);
            if(!$info_res){
                return show(config('code.error'), '当前结课数更改失败！');
            }

            if ($info['cost_type'] == 1) {
                $names = Db::name('lesson_comment')
                    ->where('lesson_id', $data['lesson_id'])
                    ->where('comment_rank', '<=', 3)
                    ->select();
                // 评论表里 当前课时数 学生出席attend_lesson_num+1
                $class_name = [];
                foreach ($names as $k => $v) {
                    $class_name[] = $names[$k]['comment_id'];
                    $comment['complete_lesson_num'] = $names[$k]['complete_lesson_num'] + 1;
                    if (in_array($names[$k]['comment_id'], $data['user_id'], false)) {
                        $comment['attend_lesson_num'] = $names[$k]['attend_lesson_num'] + 1;
                    } else {
                        $comment['attend_lesson_num'] = $names[$k]['attend_lesson_num'];
                    }
                    $lc = new LessonCommentModel();
                    $lc->allowField(true)->save($comment, ['id' => $names[$k]['id']]);
                }
                // order表 complete_lesson_num// escape_lesson_num
                $escape = array_diff($class_name, $data['user_id']);//请假名单
                if ($class_name) {
                    foreach ($class_name as $kk => $vv) {
                        $o_data = Db::name('order')
                            ->where('lesson_id', $data['lesson_id'])
                            ->where('user_id', $vv)
                            ->find();
                        $order['complete_lesson_num'] = $o_data['complete_lesson_num'] + 1;
                        if (in_array($o_data['user_id'], $escape, false)) {
                            $order['escape_lesson_num'] = $o_data['escape_lesson_num'] + 1;
                        } else {
                            $order['escape_lesson_num'] = $o_data['escape_lesson_num'];
                        }
                        $ord = new Order();
                        $ord->allowField(true)->save($order, ['id' => $o_data['id']]);
                    }
                }
                Db::commit(); //提交事务操作
                return show(config('code.success'), '点名成功！');
            } else if ($info['cost_type'] == 2) {
                Db::commit();//提交事务操作
                return show(config('code.error'), '获取数据失败', [], 404);
            }

        } catch (\Exception $e) {
            //事务回滚
            Db::rollback();
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * @ 教师端 确认当前课时结束 教师结课
     * @param lesson_id int 教师结课课程id 必传
     * @param comment_lesson_number int 当前课时数 必传
     * @author 巫玉梅 <1120504614@qq.com>
     */

    public function end_lesson_now()
    {
        $data = $_POST;

        if (empty($data)) {
            throw new ApiException('数据不合法',404);
        }
        // 当前结课课程id 必传
        if (empty($data['lesson_id'])) {
            throw new ApiException('lesson_id is not found',404);
        }
        // 当前结课数
        if (empty($data['comment_lesson_number'])) {
            throw new ApiException('comment_lesson_number is not found',404);
        }
        try{
            $lesson = Db::name('lesson')->where(array('id' => $data['lesson_id']))->find();

            if ($lesson['is_comment'] == 1) {
                $lesson_num = $lesson['lesson_num'];
                $comment = Db::name('lesson_comment')->where(array('lesson_id' => $data['lesson_id']))->select();
                if (!($lesson_num - $data['comment_lesson_number'] == 0 )) {
                    foreach ($comment as $k => $v) {
                        if ($data['comment_lesson_number'] !=$comment[$k]['attend_lesson_num']) {
                            $comment[$k]['attend_lesson_num'] = $data['comment_lesson_number'];//将所接收的课时数替换order表中的attend_lesson_num的课时数
                            Db::name('lesson_comment')->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))->update($comment[$k]);

                            if ($comment[$k]['comment_rank'] <= 3) {
                                $comment[$k]['comment_status'] = 1;
                                $comment[$k]['comment_lesson_number'] = $data['comment_lesson_number'];
                                $comment[$k]['comment_start_time']=time();
                                Db::name('lesson_comment')->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))->update($comment[$k]);
                            }
                        } else {
                            if ($comment[$k]['comment_rank'] <= 3) {
                                $comment[$k]['comment_lesson_number'] = $data['comment_lesson_number'];
                                $comment[$k]['comment_status'] = 0;
                                $comment[$k]['attend_lesson_num'] = $data['comment_lesson_number'];
                                $comment[$k]['comment_start_time']=time();
                                Db::name('lesson_comment')->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))->update($comment[$k]);
                            }
                        }
                    }
                } else {
                    // 默认评价的
                    foreach ($comment as $k => $v) {
                        if ($data['comment_lesson_number'] != $comment[$k]['attend_lesson_num']) {
                            $data2['attend_lesson_num'] = $data['comment_lesson_number'];
                            //将所接收的课时数替换order表中的attend_lesson_num的课时数
                            Db::name('lesson_comment')
                                ->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))
                                ->update($data2);

                            if ($comment[$k]['comment_rank'] <= 3) {
                                $data3['comment_lesson_number'] = $data['comment_lesson_number'];
                                $data3['comment_status'] = 1;
                                $data3['comment_start_time']=time();
                                Db::name('lesson_comment')->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))->update($data3);
                            }
                        } else {
                            if ($comment[$k]['comment_rank'] <= 3) {
                                $data4['comment_lesson_number'] = $data['comment_lesson_number'];
                                $data4['comment_status'] = 1;
                                //$data4['attend_lesson_num'] = $data['comment_lesson_number'];
                                Db::name('lesson_comment')->where(array('comment_id' => $comment[$k]['comment_id'], 'lesson_id' => $comment[$k]['lesson_id']))->update($data4);
                            }
                        }
                    }
                }

                return show(config('code.success'),'结课成功');
            } else {  //不需要评论的
                $names_c = Db::name('lesson_comment')->where(array('lesson_id' => $data['lesson_id']))->select();
                foreach ($names_c as $k1 => $v1) {
                    $data5['comment_lesson_number'] = $data['comment_lesson_number'];
                    Db::name('lesson_comment')->where(array('lesson_id' => $data['lesson_id'], 'comment_id' => $names_c[$k1]['comment_id']))->update($data5);
                }
                return show(config('code.success'),'教师结课成功！');
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }
}